package college.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFCellUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import college.constants.Constants;
import college.dao.Attendance;
import college.dao.AttendanceId;
import college.dao.Branch;
import college.dao.ContactDetails;
import college.dao.Student;
import college.exception.IIETException;
import college.model.AttendanceFormModel;
import college.model.FileUploadModel;
import college.service.CollegeService;
import college.util.ExcelFileGenerator;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	CollegeService collegeService;

	@RequestMapping(value = "/iservicehome")
	public String iserviceHome(@ModelAttribute("branch") Branch branch) {
		System.out.println("HomeController: Passing through iservicehome...");
		return "iservicehome";
	}
	
	@RequestMapping(value = "/adminhome")
	public String adminHome() {
		System.out.println("HomeController: Passing through adminhome...");
		return "adminhome";
	}

	@RequestMapping(value = "/branchform")
	public String branchForm(@ModelAttribute("branch") Branch branch) {
		System.out.println("HomeController: Passing through branchform...");
		return "branchform";
	}

	@RequestMapping(value = "/savebranch")
	public String saveBranch(@ModelAttribute("branch") Branch branch,
			Model model) {
		System.out.println("HomeController: Passing through savebranch...");
		try {
			collegeService.saveBranch(branch);

			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (IIETException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}

		return "branchform";
	}

	@RequestMapping(value = "/studentform")
	public String studentForm(@ModelAttribute("student") Student student,
			Model model) {
		System.out.println("HomeController: Passing through studentform...");
		model.addAttribute("branchList", collegeService.findAllBranches());

		return "studentform";
	}

	@RequestMapping(value = "/savestudent")
	public String saveStudent(@ModelAttribute("student") Student student,
			BindingResult bindingResult, Model model) {
		System.out.println("HomeController: Passing through savestudent...");
		try {
			student.getContactDetails().setCid(student.getHtno().toUpperCase());
			student.getContactDetailses().add(student.getContactDetails());
			collegeService.saveStudent(student);
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (IIETException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}
		// ModelAndView mv = new ModelAndView("studentform", "command",
		// student);
		// mv.addObject("branchList", collegeService.findAllBranches());
		model.addAttribute("branchList", collegeService.findAllBranches());
		return "studentform";
	}

	@RequestMapping(value = "/attendancehome")
	public String attendanceHome() {
		System.out.println("HomeController: Passing through attendancehome...");
		return "attendancehome";
	}

	@RequestMapping(value = "/selectclass")
	public String selectClass(Model model) {
		System.out.println("HomeController: Passing through selectclass...");
		model.addAttribute("branchList", collegeService.findAllBranches());
		
		return "selectclass";
	}

	@Secured({ "ROLE_ATT_WRITE" })
	@RequestMapping(value = "/attendanceform")
	public String attendanceForm(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model, Principal principal) {
		System.out.println("HomeController: Passing through attendanceform...");

		List<Student> studentList = collegeService.findAllstudents(
				attendanceFormModel.getBranchCode(),
				attendanceFormModel.getYear(), attendanceFormModel.getSem(),attendanceFormModel.getSection());
		model.addAttribute("studentList", studentList);

		return "attendanceform";
	}

	@Secured({ "ROLE_ATT_WRITE" })
	@RequestMapping(value = "/saveattendance")
	public String saveAttendance(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out
				.println("HomeController: Passing through savesattendance...");

		List<Attendance> alist = new ArrayList<Attendance>();
		Student student = null;
		for (Attendance attendance : attendanceFormModel.getAttendanceList()) {
			try {
				try {
					Date d = new SimpleDateFormat("dd-MM-yyyy")
							.parse(attendanceFormModel.getDate());
					if (attendance.getId() != null) {
						student = attendance.getId().getStudent();
						// student.setHtno(htno)
						AttendanceId id = new AttendanceId(d,
								attendanceFormModel.getHour(), student);
						attendance.setId(id);
						attendance.setFaculty(attendanceFormModel.getFaculty());
						attendance.setSubject(attendanceFormModel.getSubject());
						// attendance.setAttendance(attendanceFormModel.get)
						alist.add(attendance);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw new IIETException(e.getMessage());

				}
				model.addAttribute("successMessage",
						Constants.SAVED_SUCCESSFULLY);
			} catch (IIETException exception) {
				model.addAttribute("errorMessage", exception.getErrorMessage());
			}

		}
		collegeService.saveAttendance(alist);
		/*model.addAttribute("studentList", collegeService.findAllstudents(
				attendanceFormModel.getBranchCode(),
				attendanceFormModel.getYear(), attendanceFormModel.getSem()));*/
		return "attendanceform";
	}

	@RequestMapping(value = "/attendancesearchform")
	public String attendanceSearchForm(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out
				.println("HomeController: Passing through attendancesearchform...");

		model.addAttribute("branchList", collegeService.findAllBranches());
		return "attendancesearchform";
	}

	@RequestMapping(value = "/searchattendance")
	public String searchAttendance(@RequestParam("date") String date,
			@RequestParam("hour") String hour,
			@RequestParam("branch") String branch,
			@RequestParam("year") String year,
			@RequestParam("section") String section, Model model) {
		System.out
				.println("HomeController: Passing through searchattendance...");
		List<Attendance> attendanceList = null;
		try {
			attendanceList = collegeService.findAttendance(date, hour, branch,
					year, section);
			// attendanceList = collegeService.findAllAttendance();
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (IIETException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}

		model.addAttribute("attendanceList", attendanceList);
		model.addAttribute("date", date);
		model.addAttribute("hour", hour);
		model.addAttribute("branch", branch);
		model.addAttribute("year", year);
		model.addAttribute("section", section);

		return "attendancereport";
	}

	@RequestMapping(value = "/loginform")
	public String loginForm(HttpServletRequest request) {
		System.out.println("HomeController: Passing through loginform...");
		// WebApplicationContextUtils.getWebApplicationContext()
		return "login";
	}

	@RequestMapping(value = "/generateexcel")
	public String generateExcel(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Attendance> attendanceList = (List<Attendance>) request
				.getSession().getAttribute("attendanceList");
		System.out.println("HomeController: Passing through generateexcel...");

		Object[][] data = new Object[attendanceList.size()][];
		int i = 0;
		for (Attendance attendance : attendanceList) {
			Student student = attendance.getId().getStudent();
			ContactDetails contactDetails = (ContactDetails) student
					.getContactDetailses().toArray()[0];
			data[i] = new Object[] { ++i, student.getHtno(), student.getName(),
					attendance.getAttendance(),
					contactDetails.getParentMobile1() };
		}
		ExcelFileGenerator.createExcelFile("c:\\attendance.xls",
				Constants.headings, data);

		try {

			OutputStream out = response.getOutputStream();
			// response.setContentType("text/plain; charset=utf-8");
			response.setContentType("application/xls"); // in my example this
														// was an xls file
			Calendar calendar = Calendar.getInstance();
			response.setHeader(
					"Content-Disposition",
					"attachment; filename=attendace-"
							+ calendar.get(Calendar.DATE) + "-"
							+ (calendar.get(Calendar.MONTH) + 1) + "-"
							+ calendar.get(Calendar.YEAR) + ".xls");
			FileInputStream fi = new FileInputStream("c:\\attendance.xls");
			IOUtils.copy(fi, out);
			out.flush();
			out.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// model.addAttribute("attendanceList", attendanceList);
		return null;
	}

	@RequestMapping(value = "/loginsuccess")
	public String loginSuccess(HttpServletRequest request) {

		List l = (List) SecurityContextHolder.getContext().getAuthentication()
				.getAuthorities();
		request.getSession(false).getServletContext()
				.setAttribute("branch", l.get(0).toString());
		System.out.println("HomeController: Passing through iservicehome...");
		return "iservicehome";
	}

	@RequestMapping(value = "/accessdenied")
	public String doSomething() {
		System.out.println("HomeController: Passing through iservicehome...");
		return "accessdenied";
	}

	@RequestMapping(value = "/loginfailed")
	public String loginerror(Model model) {

		model.addAttribute("error", "true");
		return "login";

	}

	@RequestMapping(value = "/uploadstudentform")
	public String uploadStudentForm(
			@ModelAttribute("fileUploadModel") FileUploadModel fileUploadModel,
			Model model) {
		// model.addAttribute(new FileUploadModel());
		return "uploadstudentform";

	}

	@RequestMapping(value = "/uploadstudents")
	public String uploadStudents(FileUploadModel fileUploadModel,
			BindingResult result, HttpServletRequest request,
			HttpServletResponse response, HttpSession session, Model model) {
		String fileName = null;
		int i = -1;
		try{
		try {
			MultipartFile file = fileUploadModel.getFile();

			InputStream inputStream = null;
			OutputStream outputStream = null;
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				/*
				 * if (file.getSize() > 10000) {
				 * System.out.println("File Size:::" + file.getSize()); return
				 * "/uploadfile"; }
				 */
				System.out.println("size::" + file.getSize());
				String path = request.getContextPath();
				// fileName =
				// request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"+
				// file.getOriginalFilename();
				fileName = "c:/uploads/" + file.getOriginalFilename();
				/*
				 * fileName = request.getRealPath("") + "/uploaded/" +
				 * file.getOriginalFilename();
				 */
				outputStream = new FileOutputStream(fileName);
				System.out.println("fileName:" + file.getOriginalFilename());

				int readBytes = 0;
				byte[] buffer = new byte[10000];
				while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
					outputStream.write(buffer, 0, readBytes);
				}
				outputStream.close();
				inputStream.close();
			}

			// ..........................................

		} catch (Exception e) {
			e.printStackTrace();
		}

		HSSFWorkbook book = null;

		
	
			try {
				FileInputStream inputStream = new FileInputStream(fileName);
				try {
					book = new HSSFWorkbook(inputStream);
					HSSFSheet sheet = book.getSheetAt(0);

					Iterator rowIterator = sheet.rowIterator();

					while (rowIterator.hasNext()) {
						HSSFRow row = (HSSFRow) rowIterator.next();
						if (i == -1) {
							i++;
							continue;
						}

						Student student = new Student();
						Branch branch = new Branch();
						ContactDetails contactDetails = new ContactDetails();
						// HSSFCellUtil.
						HSSFCell htno = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_HTNO);
						HSSFCell name = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_NAME);
						HSSFCell branchCode = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_BRANCH);
						HSSFCell year = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_YEAR);
						HSSFCell sem = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_SEM);
						HSSFCell section = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_SECTION);
						// HSSFCellUtil.sesetCellType(Cell.CELL_TYPE_STRING);

						HSSFCell mobile = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_MOBILE);
						mobile.setCellType(Cell.CELL_TYPE_STRING);
						HSSFCell email = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_EMAIL);
						HSSFCell fatherName = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_FATHERNAME);
						HSSFCell parentMobile1 = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_PARENTMOBILE1);
						parentMobile1.setCellType(Cell.CELL_TYPE_STRING);
						HSSFCell parentMobile2 = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_PARENTMOBILE2);
						parentMobile2.setCellType(Cell.CELL_TYPE_STRING);
						HSSFCell address = HSSFCellUtil.getCell(row,
								Constants.STUDENT_EXCEL_ADDRESS);

						if (branch != null) {
							branch.setCode(branchCode.toString());
							student.setBranch(branch);
						}
						if (htno != null) {
							student.setHtno(htno.toString());
							contactDetails.setCid(htno.toString());
						}
						if (name != null)
							student.setName(name.toString());
						if (year != null)
							student.setYear(Constants.YEAR_MAP.get(year
									.toString()));
						if (sem != null)
							student.setSem(Constants.YEAR_MAP.get(sem
									.toString()));
						if (section != null)
							student.setSection(section.toString());

						// Double m = ;
						String s = mobile.getStringCellValue();

						if (mobile != null)
							contactDetails.setMobile(mobile.toString());
						if (email != null)
							contactDetails.setEmail(email.toString());
						if (fatherName != null)
							contactDetails.setFatherName(fatherName.toString());
						if (parentMobile1 != null)
							contactDetails.setParentMobile1(parentMobile1
									.toString());
						if (parentMobile2 != null)
							contactDetails.setParentMobile2(parentMobile2
									.toString());
						if (address != null)
							contactDetails.setAddress(address.toString());

						collegeService.saveStudent(student);
						collegeService.saveContactDetails(contactDetails);
						i++;

					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

					throw new IIETException(e.getMessage());

				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();

				throw new IIETException(e.getMessage());

			}
		} catch (IIETException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}

		// List list = ExcelFileReader.getExcelData(fileName);
		model.addAttribute("successfulUploadCount", i);
		return "uploadstudentform";

	}
}